<style scoped>
.three-canvas {
  width: 100%;
  height: 100%;
  display: block;
}
</style>

<template><canvas class="three-canvas" ref="canvas"></canvas></template>

<script setup>
import { onMounted, onBeforeUnmount, ref } from 'vue'
import { emit } from '../../utils/EventBus.js'
import { ThreeScene, THREE_SCENE_INITIALIZATION, THREE_SCENE_DESTROY } from './ThreeScene.js'

const canvas = ref(null)
const { sceneName, contextOptions } = defineProps({
  sceneName: {
    type: String,
    required: true,
  },
  contextOptions: {
    type: Object,
    default: () => ({}),
  },
})

onMounted(() => {
  const scene = new ThreeScene({
    name: sceneName,
    context: { canvas: canvas.value, ...contextOptions }
  })
  ThreeScene.setInstance(sceneName, scene)

  if (sceneName === 'threeScene') {
    window.threeScene = scene
  }
  emit(THREE_SCENE_INITIALIZATION, sceneName)
})

onBeforeUnmount(() => {
  const scene = ThreeScene.getInstance(sceneName)
  if (scene) {
    emit(THREE_SCENE_DESTROY, sceneName)
    requestAnimationFrame(() => {
      threeSceneMap.delete(sceneName)
      scene.destroy()
    })
  }
})

</script>
